<?php

namespace common\models\user;

use Yii;
use common\models\shop\ShopProduct;

/**
 * This is the model class for table "{{%user_history}}".
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property string $model 模型
 * @property int $model_id 模型ID
 * @property int $views 30天内次数
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class UserHistory extends \common\db\ActiveRecord {

    const MODEL_SPU = 'spu';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_history}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'model_id', 'views', 'created_at', 'updated_at'], 'integer'],
            [['model'], 'required'],
            [['model'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'model' => '模型',
            'model_id' => '模型ID',
            'views' => '30天内次数',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getSource() {
        if ($this->model == static::MODEL_SPU) {
            return $this->hasOne(ShopProduct::className(), ['id' => 'model_id'])->active(ShopProduct::STATUS_ACTIVE);
        }
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public static function record($uid, $model, $model_id) {
        $instance = static::findOrNew([
            'user_id' => $uid,
            'model' => $model,
            'model_id' => $model_id,
        ]);
        $instance->views = $instance->views + 1;
        return $instance->save(false);
    }

    /**
     * {@inheritdoc}
     */
    public function getName() {
        if ($this->source) {
            return $this->source->name;
        }
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function getThumb() {
        if ($this->source) {
            return $this->source->thumb;
        }
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription() {
        if ($this->source) {
            return $this->source->description;
        }
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function getWeblink() {
        if ($this->source) {
            return $this->source->nativelink;
        }
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'name',
            'description',
            'thumb',
            'views',
            'weblink',
        ];
    }

}
